package com.central.apps.controller;

import cn.hutool.core.map.MapUtil;
import com.central.app.service.HandlerService;
import com.central.apps.entity.BlMessage;
import com.central.apps.service.MessageService;
import net.sf.json.JSONObject;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.xml.crypto.Data;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 采购计划接口类
 *
 * @author 李大超
 * @date 2022/10/15
 */
@RestController
public class PurchasePlanController {
    @Autowired
    private HandlerService handlerService;
    @Autowired
    private MessageService messageService;
    @PostMapping("/generatePO")
    public String generatePO(@RequestBody Map<String,Object> params) throws Exception {
        List<Map<String, Object>> maps = new ArrayList<>();
        HashMap<String, Object> hashMap = new HashMap<>();
        JSONObject json = new JSONObject();
        json.put("code", "0");
        String ppid = MapUtils.getString(params,"ppid");
        String status = MapUtils.getString(params,"status");

        // 判断流程状态-已批准
        if (!"已批准".equals(status)) {
            json.put("code", "1");
            json.put("msg", "流程未审批通过, 请审批通过后再生成订单!");
            return json.toString();
        }

        // 查询采购计划信息
        List<Map<String, Object>> ppList = handlerService.findBySql("select * from gq_purchaseplan where id = " + ppid);
        String procurexetor = MapUtils.getString(ppList.get(0), "procurexetor");
        String procurexetorid = MapUtils.getString(ppList.get(0), "procurexetorid");
        hashMap.put("procurexetor",procurexetor);
        hashMap.put("procurexetorid",procurexetorid);
        if (CollectionUtils.isNotEmpty(ppList)) {
            //
            List<Map<String, Object>> ppslList1 = handlerService.findBySql("select * from gq_ppsummaryline where converttopo = 2 and ppid = " + ppid);
            if (CollectionUtils.isNotEmpty(ppslList1)){
                for (int i=0;i<ppslList1.size();i++){
                    String itemnum = MapUtils.getString(ppslList1.get(i), "itemnum");
                    json.put("code", "1");
                    json.put("msg", ""+itemnum+"物料已达到计划数量，无法再次生成!");
                    return json.toString();
                }
            }
            // 获取采购计划明细信息
            List<Map<String, Object>> ppslList = handlerService.findBySql("select * from gq_ppsummaryline where converttopo = 0 and ppid = " + ppid);

            if (CollectionUtils.isEmpty(ppslList)) {
                json.put("code", "1");
                json.put("msg", "已生成相关订单，不能再次生成!");
                return json.toString();
            }


            // 获取采购申请信息
            Map<String, Object> ppMap = ppList.get(0);

            String id = MapUtils.getString(ppMap,"id");
            String description = MapUtils.getString(ppMap,"description");
            String requireddate = MapUtils.getString(ppMap,"requireddate");
            String createuser = MapUtils.getString(ppMap,"createuser");
            String createuserdesc = MapUtils.getString(ppMap,"createuserdesc");
            String orgcode = MapUtils.getString(ppMap,"orgcode");
            String sitecode = MapUtils.getString(ppMap,"sitecode");
            String deptcode = MapUtils.getString(ppMap,"deptcode");

            // 组织采购订单信息
            Map<String, Object> map = new HashMap<>();
            map.put("requireddate", requireddate);
            map.put("description", description);
            map.put("suppliernum","");
            map.put("suppliername","");

            // 生成采购订单编码
            Map<String, Object> poMap = new HashMap<>();
            handlerService.addBizNum("poApp", "gq_po", poMap);
            // 查询采购订单编码
            String ponum = (String) poMap.get("ponum");
            hashMap.put("ponum",ponum);
            maps.add(hashMap);
            map.put("ponum", ponum);
            map.put("ppid", id);
            map.put("status", "新建");
            map.put("createuser", createuser);
            map.put("createuserdesc", createuserdesc);
            hashMap.put("createuser",createuser);
            hashMap.put("createuserdesc",createuserdesc);
            map.put("ppnum", MapUtils.getString(ppMap,"ppnum"));
            map.put("ppdesc", MapUtils.getString(ppMap,"description"));
            map.put("purchasetype", MapUtils.getString(ppMap,"purchasemethod"));
            map.put("purchasecategory", MapUtils.getString(ppMap,"purchasecategory"));
            map.put("haschild", 1);

            // 总公司、分公司、部门编码空值
            map.put("orgcode", orgcode);
            map.put("sitecode", sitecode);
            map.put("deptcode", deptcode);

            // 插入采购订单信息
            BigInteger poid = (BigInteger) handlerService.insert( "gq_po", map);
            LocalDateTime currentDateTime = LocalDateTime.now();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String formattedDateTime = currentDateTime.format(formatter);
            hashMap.put("createtime",formattedDateTime);
            String id6="";
            List<Map<String, Object>> poslineDatas = new ArrayList<>();
            for (Map<String, Object> ppslMap : ppslList) {
                Integer ppslid = (Integer) ppslMap.get("id");
                // 组织询价单明细数据
                Map<String, Object> poslineMap = new HashMap<>();
                poslineMap.put("ppid", ppslMap.get("ppid"));
                poslineMap.put("ppslid", ppslid);
                poslineMap.put("poid", poid);
                poslineMap.put("ponum",ponum);
                poslineMap.put("itemnum", ppslMap.get("itemnum"));
                List<Map<String, Object>> itemnum = handlerService.findBySql("select taxrate,id from gq_item where itemnum='" + ppslMap.get("itemnum") + "'");
                Map<String, Object> map1 = itemnum.get(0);
                Float taxrate = MapUtils.getFloat(map1, "taxrate");
                id6 = MapUtils.getString(map1, "id");
                //poslineMap.put("itemid",id6);
                Date date = new Date();
                poslineMap.put("taxrate", taxrate);
                poslineMap.put("itemdesc", ppslMap.get("itemdesc"));
                poslineMap.put("qualitygrade", ppslMap.get("qualitygrade"));
                poslineMap.put("specifications",ppslMap.get("specifications"));
                poslineMap.put("spemodel", ppslMap.get("spemodel"));
                poslineMap.put("packform", ppslMap.get("packform"));
                poslineMap.put("model", ppslMap.get("model"));
                poslineMap.put("commertime",date);
                poslineMap.put("orderunit", ppslMap.get("orderunit"));
                poslineMap.put("maintechtors", ppslMap.get("maintechtors"));
                poslineMap.put("manufacturer", ppslMap.get("manufacturer"));
                poslineMap.put("orderqty", ppslMap.get("orderqty"));
                poslineMap.put("number",ppslMap.get("orderqty"));
                poslineMap.put("qualquantity",ppslMap.get("orderqty"));
                poslineMap.put("unitcost", ppslMap.get("unitcost"));
                poslineMap.put("totalcost", ppslMap.get("totalcost"));
                poslineMap.put("demount",ppslMap.get("totalcost"));
                poslineMap.put("proid", ppslMap.get("proid"));
                poslineMap.put("subjectno", ppslMap.get("subjectno"));
                poslineMap.put("purchasetype", ppslMap.get("purchasemethod"));
                poslineMap.put("isinspection", ppslMap.get("isinspection"));
                poslineMap.put("uninspectqty", ppslMap.get("orderqty"));
                poslineMap.put("inspectqty", 0);
                poslineMap.put("unrejectedqty", ppslMap.get("orderqty"));
                poslineMap.put("rejectedqty", 0);
                poslineMap.put("unreceivedqty", ppslMap.get("orderqty"));
                poslineMap.put("receivedqty", 0);
                poslineMap.put("receivedlinecost", 0);
                poslineMap.put("receivedunitcost", 0);
                poslineMap.put("receivedtotalcost", 0);
                poslineMap.put("reamount",0);
                poslineDatas.add(poslineMap);
                // 更新采购计划行标记信息
                handlerService.updateBySql("update gq_ppsummaryline set converttopo = 1 where id = " + ppslid);
            }

            // 批量插入询价单明细
            handlerService.batchInsert("poApp","gq_posline", poslineDatas);
            List<Map<String, Object>> bySql1 = handlerService.findBySql("select * from gq_posline where ponum='" + ponum + "' and poid=" + poid + "");
            if (CollectionUtils.isNotEmpty(bySql1)){
                for (int i=0;i<bySql1.size();i++){
                    Map<String, Object> map1 = bySql1.get(i);
                    String id1 = MapUtils.getString(map1, "id");
                    Float taxrate = MapUtils.getFloat(map1, "taxrate");
                    String totalcost = MapUtils.getString(map1, "totalcost");
                    BigDecimal bigDecimal6 = new BigDecimal(totalcost);
                    String taxrate1 = String.valueOf(taxrate);
                    BigDecimal bigDecimal = new BigDecimal(taxrate1);
                    BigDecimal bigDecimal3 = new BigDecimal("1");
                    BigDecimal bigDecimal4 = new BigDecimal("0");
                    //:unitcost*:orderqty/(1+:taxrate)无税金额
                    bigDecimal4=bigDecimal6.divide(bigDecimal.add(bigDecimal3),2,BigDecimal.ROUND_HALF_UP);
                    //double f1 = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();

                    //:unitcost*:orderqty-:unitcost*:orderqty/(1+:taxrate)//税额
                    BigDecimal bigDecimal5 = new BigDecimal("0");
                    //ma.subtract(mb)
                    bigDecimal5=bigDecimal6.subtract(bigDecimal4);
                    handlerService.updateBySql("update gq_posline set itemid="+id6+",taxrate='"+taxrate+"',amexclutax='"+bigDecimal4+"',taxamount='"+bigDecimal5+"' where id="+id1);
                }
            }
            List<Map<String, Object>> polineDatas = new ArrayList<>();
            float poTotalcost = 0f;
            //便利订单会总行
            List<Map<String, Object>> bySql = handlerService.findBySql("select * from gq_posline where poid='" + poid + "'");
            if (CollectionUtils.isNotEmpty(bySql)){
                for (int x=0;x<bySql.size();x++){
                    Map<String, Object> map1 = bySql.get(x);
                    String ppslid = MapUtils.getString(map1, "ppslid");
                    String id1 = MapUtils.getString(map1, "id");
                    // 获取采购计划明细信息
                    List<Map<String, Object>> pplList = handlerService.findBySql("select * from gq_ppline where  ppslid = '" + ppslid+"' and ppid = " + ppid);
                    for (Map<String, Object> pplMap : pplList) {
                        //获取会总行id
                        int pplid = (int) pplMap.get("id");
                        float orderqty = (float) pplMap.get("orderqty");
                        //float linecost = (float) pplMap.get("linecost");
                        BigDecimal linecost = new BigDecimal(0);
                        // 组织采购订单明细数据
                        Map<String, Object> polineMap = new HashMap<>();
                        polineMap.put("poslid", id1);//ppslid计划会总行id
                        polineMap.put("poid", poid);//采购订单Id
                        polineMap.put("ponum", ponum);

                        String unitcost="";
                        List<Map<String, Object>> bySql2 = handlerService.findBySql("select unitcost from gq_posline where ponum='" + ponum + "' and id='" + id1 + "'");
                        if (CollectionUtils.isNotEmpty(bySql2)){
                            Map<String, Object> map2 = bySql2.get(0);
                            unitcost= MapUtils.getString(map2, "unitcost");
                        }
                        BigDecimal bigDecimal=new BigDecimal(unitcost);
                        polineMap.put("ppid", pplMap.get("ppid"));
                        polineMap.put("pplid", pplMap.get("id"));
                        polineMap.put("ppslid", pplMap.get("ppslid"));
                        polineMap.put("proid", pplMap.get("proid"));
                        polineMap.put("taskid", pplMap.get("taskid"));
                        polineMap.put("prid", pplMap.get("prid"));
                        polineMap.put("prlid", pplMap.get("prlid"));
                        polineMap.put("pplinenum", pplMap.get("pplinenum"));
                        polineMap.put("ppnum", pplMap.get("ppnum"));
                        polineMap.put("prnum", pplMap.get("prnum"));
                        polineMap.put("type",pplMap.get("type"));
                        polineMap.put("requestedby", createuser);
                        polineMap.put("reqdeptcode", deptcode);
                        polineMap.put("specifications",pplMap.get("specifications"));
                        polineMap.put("occupnot",pplMap.get("occupnot"));
                        polineMap.put("applyby",pplMap.get("applyby"));
                        polineMap.put("itemtype", pplMap.get("itemtype"));
                        polineMap.put("itemnum", pplMap.get("itemnum"));
                        polineMap.put("itemdesc", pplMap.get("itemdesc"));
                        polineMap.put("spemodel", pplMap.get("spemodel"));
                        polineMap.put("qualitygrade", pplMap.get("qualitygrade"));
                        polineMap.put("manufacturer", pplMap.get("manufacturer"));
                        polineMap.put("packform", pplMap.get("packform"));
                        polineMap.put("maintechtors", pplMap.get("maintechtors"));
                        polineMap.put("model", pplMap.get("model"));
                        polineMap.put("orderqty", orderqty);
                        polineMap.put("arrquantity",orderqty);
                        polineMap.put("uninspectqty", orderqty);
                        polineMap.put("inspectqty", 0);
                        polineMap.put("unrejectedqty", orderqty);
                        polineMap.put("rejectedqty", 0);
                        polineMap.put("unreceivedqty", orderqty);
                        polineMap.put("receivedqty", 0);
                        polineMap.put("receivedlinecost", 0);
                        polineMap.put("receivedunitcost", 0);
                        polineMap.put("receivedtotalcost", 0);

                        polineMap.put("orderunit", pplMap.get("orderunit"));
                        polineMap.put("unitcost", bigDecimal);
                        polineMap.put("taxcode", pplMap.get("taxcode"));
                        polineMap.put("taxrate", pplMap.get("taxrate"));
                        BigDecimal bigDecimal1 = new BigDecimal(orderqty);
                        linecost = bigDecimal.multiply(bigDecimal1);
                        polineMap.put("linecost", linecost);

                        polineMap.put("isinspection", pplMap.get("isinspection"));
                        polineMap.put("inspectionreq", pplMap.get("inspectionreq"));
                        polineMap.put("whfournew", pplMap.get("whfournew"));
                        polineMap.put("whethdangerous", pplMap.get("whethdangerous"));
                        polineMap.put("advisupplier", pplMap.get("advisupplier"));
                        polineMap.put("contacts", pplMap.get("contacts"));
                        polineMap.put("phone", pplMap.get("phone"));
                        polineMap.put("rearecommendation", pplMap.get("rearecommendation"));
                        polineMap.put("reqdeliverydate", pplMap.get("reqdeliverydate"));
                        polineMap.put("acceptments", pplMap.get("acceptments"));
                        polineMap.put("wheprocuremen", pplMap.get("wheprocuremen"));
                        polineMap.put("commerceorder", pplMap.get("commerceorder"));
                        polineMap.put("reasonpur", pplMap.get("reasonpur"));

                        polineMap.put("production", pplMap.get("production"));
                        polineMap.put("requiredtime", pplMap.get("requiredtime"));
                        polineMap.put("unifiedno", pplMap.get("unifiedno"));
                        polineMap.put("researchmode", pplMap.get("researchmode"));
                        polineMap.put("productmode", pplMap.get("productmode"));
                        polineMap.put("purchasemethod", pplMap.get("purchasemethod"));
                        polineMap.put("invitationmethod", pplMap.get("invitationmethod"));
                        polineMap.put("purchasenote", pplMap.get("purchasenote"));
                        polineMap.put("subjectno",pplMap.get("subjectno"));
                        polineMap.put("typeline",pplMap.get("typeline"));
                        polineDatas.add(polineMap);

                        // 更新采购订单
                        poTotalcost = poTotalcost + linecost.floatValue();
                        handlerService.updateBySql("update gq_ppline set converttopo = 1 where id = " + pplid);
                    }
                }
            }


            // 批量插入采购订单明细
            handlerService.batchInsert("poApp","gq_poline", polineDatas);

            // 更新采购订单
            handlerService.updateBySql("update gq_po set totalcost = " + poTotalcost + " where id = " + poid);
            sendMessage(maps);
        }
        json.put("code", "0");
        json.put("msg", "生成采购订单成功, 请到采购订单界面查询数据!");
        return json.toString();
    }

    private void sendMessage(List<Map<String, Object>> maps) {
        if(CollectionUtils.isNotEmpty(maps)){
            for (int i=0;i<maps.size();i++){
                Map<String, Object> map = maps.get(i);
                String procurexetor = MapUtils.getString(map, "procurexetor");
                String procurexetorid = MapUtils.getString(map, "procurexetorid");
                List<Map<String, Object>> bySql1 = handlerService.findBySql("select id,nickname from sys_user where field10 = " + procurexetorid + " limit 1");
                if (CollectionUtils.isNotEmpty(bySql1)){
                    Map<String, Object> map1 = bySql1.get(0);
                    String id = MapUtils.getString(map1, "id");
                    String nickname = MapUtils.getString(map1, "nickname");
                    String ponum = MapUtils.getString(map, "ponum");
                    Date createtime = MapUtil.getDate(map, "createtime");
                    String createuser = MapUtils.getString(map, "createuser");
                    String createuserdesc = MapUtils.getString(map, "createuserdesc");
                    BlMessage message = new BlMessage();
                    message.setRecipient(id);
                    message.setRecipientname(nickname);
                    message.setCreatetime(createtime);
                    message.setIsshow("未读");
                    String str = "";
//                stringBuilder.append("<a href= '").append("#/messageViewDetail?appName=poApp&amp;fieldName=ponum&amp;fieldValue=")
//                        .append(ponum).append("'").append(" rel='noopener noreferrer'").append(" target='_blank'>").append(ponum);
//                msgformat = "<p>"+stringBuilder.toString()+"</a>"+"订单中"+itemdesc+"物料，应于"+expectdeldate+"到货，请核查。"+"</p>";
                    StringBuilder stringBuilder = new StringBuilder();
                    stringBuilder.append("<a href= '").append("#/messageViewDetail?appName=poApp&amp;fieldName=ponum&amp;fieldValue=")
                            .append(ponum).append("'").append(" rel='noopener noreferrer'").append(" target='_blank'>").append(ponum);
                    str="<p>"+stringBuilder.toString()+"</a>"+",采购订单已生成"+"</p>";
                    message.setContent(str);
                    message.setTitle("生成采购订单");
                    message.setCreateuser(createuser);
                    message.setCreateuserdesc(createuserdesc);
                    message.setStatus("未读");
                    message.setVersion("1");
                    Map<String, Object> map2 = new HashMap<>();
                    handlerService.addBizNum("messageApp","gq_message",map2);
                    String messagenum = MapUtils.getString(map2, "messagenum");
                    message.setMessagenum(messagenum);
                    int res = messageService.addMessage(message);
                }

            }
        }
    }

    @PostMapping("/generateIS")
    public String generateIS(@RequestBody Map<String,Object> params) throws Exception {
        JSONObject json = new JSONObject();

        String ppid = MapUtils.getString(params,"ppid");
        String status = MapUtils.getString(params,"status");

        // 判断流程状态-已批准
        if (!status.equals("已批准")) {
            json.put("code", "1");
            json.put("msg", "流程未审批通过, 请审批通过后再生成询价单!");
            return json.toString();
        }

        // 查询采购计划信息
            List<Map<String, Object>> ppList = handlerService.findBySql("select * from gq_purchaseplan where id = " + ppid);

        if (CollectionUtils.isNotEmpty(ppList)) {
            // 获取采购计划明细信息
            //更改询价单状态
            String rfqnot="已询价";
            handlerService.updateBySql("update gq_purchaseplan set rfqnot='"+rfqnot+"' where  id = " + ppid);
            List<Map<String, Object>> ppslList = handlerService.findBySql("select * from gq_ppsummaryline where converttorfq = 0 and ppid = " + ppid);

            if (CollectionUtils.isEmpty(ppslList)) {
                json.put("code", "1");
                json.put("msg", "已生成相关询价单，不能再次生成!");
                return json.toString();
            }

            // 获取采购计划信息
            Map<String, Object> ppMap = ppList.get(0);
            // 组织询价单信息
            Map<String, Object> map = new HashMap<>();
            map.put("description", MapUtils.getString(ppMap,"description"));
            map.put("closeondate", MapUtils.getString(ppMap,"requireddate"));
            map.put("requireddate", MapUtils.getString(ppMap,"createtime"));
            map.put("requestedby", MapUtils.getString(ppMap,"createuser"));
            map.put("reqdeptcode", MapUtils.getString(ppMap,"deptcode"));

            // 生成询价单编码
            Map<String, Object> isMap = new HashMap<>();
            handlerService.addBizNum("inquirysheetApp", "gq_inquirysheet", isMap);
            // 查询采购订单编码
            String isnum = (String) isMap.get("isnum");
            map.put("isnum", isnum);
            map.put("status", "新建");
            map.put("ppid", ppMap.get("id"));
            map.put("ppnum", MapUtils.getString(ppMap,"ppnum"));
            map.put("ppdesc", MapUtils.getString(ppMap,"description"));
            map.put("purchasetype", MapUtils.getString(ppMap,"purchasemethod"));
            map.put("type",1);
            // 总公司、分公司、部门编码空值
            map.put("orgcode", MapUtils.getString(ppMap,"orgcode"));
            map.put("sitecode", MapUtils.getString(ppMap,"sitecode"));
            map.put("deptcode", MapUtils.getString(ppMap,"deptcode"));


            // 插入采购订单信息
            BigInteger isid = (BigInteger) handlerService.insert( "gq_inquirysheet", map);

            List<Map<String, Object>> islineDatas = new ArrayList<>();
            for (Map<String, Object> ppslMap : ppslList) {
                Integer ppslid = (Integer) ppslMap.get("id");
                // 组织询价单明细数据
                Map<String, Object> islineMap = new HashMap<>();
                islineMap.put("ppid", ppslMap.get("ppid"));
                islineMap.put("ppslid", ppslid);
                islineMap.put("isid", isid);
                islineMap.put("isnum", isnum);

                islineMap.put("itemnum", ppslMap.get("itemnum"));
                islineMap.put("itemdesc", ppslMap.get("itemdesc"));
                islineMap.put("model", ppslMap.get("model"));
                islineMap.put("specifications",ppslMap.get("specifications"));
                islineMap.put("orderqty", ppslMap.get("orderqty"));
                islineMap.put("orderunit", ppslMap.get("orderunit"));
                islineMap.put("unitcost", ppslMap.get("unitcost"));
                islineMap.put("linecost", ppslMap.get("totalcost"));
                islineMap.put("maintechtors",ppslMap.get("maintechtors"));
                islineDatas.add(islineMap);
                // 更新采购计划行标记信息
                handlerService.updateBySql("update gq_ppsummaryline set converttorfq = 1 where id = " + ppslid);
            }

            // 批量插入询价单明细
            handlerService.batchInsert("inquirysheetApp","gq_inquirysheetline", islineDatas);
        }
        json.put("code", "0");
        json.put("msg", "生成询价单成功, 请到询价单界面查询数据!");
        return json.toString();
    }
}
